export default{
  namespaced: true,
  
  state:()=>({
    // { goods_id, goods_name, goods_price, goods_count, goods_small_logo, goods_state }
    cart:JSON.parse(uni.getStorageSync('cart') || '[]')
  }),
  
  mutations:{
    addToCart(state,goods){
      const findRs = state.cart.find((x)=>x.goods_id === goods.goods_id)
      // console.log(findRs)
      if(!findRs){
        state.cart.push(goods)
      }else{
        findRs.goods_count++
      }
      this.commit('m_cart/saveStorage')
    },
    saveStorage(state){
      uni.setStorageSync('cart',JSON.stringify(state.cart))
    },
    updateGoodsState(state,goods){
      const findRs = state.cart.find((x)=>x.goods_id===goods.goods_id)
      if(findRs){
        findRs.goods_state=goods.goods_state
        this.commit('m_cart/saveStorage')
      }
    },
    updateGoodsNum(state,goods){
      const findRs = state.cart.find((x)=>x.goods_id===goods.goods_id)
      if(findRs){
        findRs.goods_count=goods.goods_count
        this.commit('m_cart/saveStorage')
      }
    },
    delGoodsById(state,goods){
      state.cart = state.cart.filter((x)=>x.goods_id!==goods.goods_id)
      this.commit('m_cart/saveStorage')
    },
    updateAllGoodsState(state,newState){
      state.cart.forEach(x=>x.goods_state=newState)
      this.commit('m_cart/saveStorage')
    }
  },
  
  getters:{
    total(state){
      let c = 0
      state.cart.forEach((x)=>c += x.goods_count)
      return c
    },
    checkedCount(state){
      return state.cart.filter(x=>x.goods_state).reduce((total,item)=>total+=item.goods_count,0)
    },
    GoodsPrice(state){
      return state.cart.filter(x=>x.goods_state).reduce((total,item)=>total+=item.goods_count*item.goods_price,0).toFixed(2)
    }
   }
}